package com.youthfilmic.yuejian.controller;

import com.youthfilmic.yuejian.dao.CommentDao;
import com.youthfilmic.yuejian.dao.SubjectDao;
import com.youthfilmic.yuejian.dao.UserDao;
import com.youthfilmic.yuejian.domain.Comment;
import com.youthfilmic.yuejian.domain.Subject;
import com.youthfilmic.yuejian.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

/**
 * Created by youweixi on 15/10/10.
 */
@Controller
@RequestMapping("/main/subject")
public class SubjectController {
    @Resource
    private SubjectDao subjectDao;
    @Resource
    private UserDao userDao;
    @Resource
    private CommentDao commentDao;

    @RequestMapping("/user/{userId}")
    public String showUserSubject(
            @PathVariable("userId") Long userId,
            @RequestParam(value="page" , required = false) Integer p,
            Model model
    ){
        if (p == null) p = 1;

        Page<Subject> page = subjectDao.findByStatusAndUserId(Subject.SATUS_SUCCEED, userId, new PageRequest(p-1, 100, new Sort(Sort.Direction.ASC, "postAt")));
        //相关话题
        Page<Subject> relate = subjectDao.findByStatus(Subject.SATUS_SUCCEED, new PageRequest(p-1, 6, new Sort(Sort.Direction.ASC, "postAt")));
        Page<Comment> comments = commentDao.findByToUserId(userId , new PageRequest(0, 5, new Sort(Sort.Direction.ASC, "postAt")));
        User user = userDao.findOne(userId);
        model.addAttribute("comments",comments.getContent());
        model.addAttribute("subjects" , page.getContent());
        model.addAttribute("relateubjects" , relate.getContent());
        model.addAttribute("user" , user);
        return "main/subject/subject-user";
    }

    @RequestMapping("/{subjectId}")
    public String showSubjectInfo(
            @PathVariable("subjectId") Long subjectId,
            Model model
    ){
        Subject subject = subjectDao.findByStatusAndId(Subject.SATUS_SUCCEED , subjectId);
        model.addAttribute("subject" , subject);
        return "main/subject/subject-single";
    }



}
